package bp.nbport.activeMQ;

import bp.da.Log;
import bp.nbport.OrgEmpCRUD;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

@Component
@ConditionalOnProperty(name="spring.activemq.listener.enabled", havingValue="true", matchIfMissing=false)
public class MsgListener {

    private static final Logger logger = LoggerFactory.getLogger(MsgListener.class);

    OrgEmpCRUD orgEmpCRUD = new OrgEmpCRUD();

    /**
     * Queue消息监听
     */
    @JmsListener(destination = "ZGB/PUSH/ZNSPTest/08Ur9" )
    public void receiveMessage(String message) {
        try {
            Thread.sleep(1000);
            logger.info("接收到的Queue消息：{}", message);
            // 判断是否是JSON格式的数据
            if(!isJson(message)){
                Log.DefaultLogWriteLineError("消息内容不是有效的JSON格式：{}", message);
                return;
            }
            orgEmpCRUD.dealOrgEmp(message);
        } catch (Exception e) {
            Log.DefaultLogWriteLineError("处理消息时发生异常", e);
        }

    }

    /**
     * Topic消息监听
     */
    @JmsListener(destination = "ZGB/PUSH/TopicTest/08Ur9", containerFactory = "jmsListenerContainerTopic")
    public void receiveTopicMessage(String message) throws Exception {
        try {
            Thread.sleep(1000);
            logger.info("接收到的Topic消息：{}", message);
            // 判断是否是JSON格式的数据
            if(!isJson(message)){
                Log.DefaultLogWriteLineError("消息内容不是有效的JSON格式：{}", message);
                return;
            }
            orgEmpCRUD.dealOrgEmp(message);
        } catch (Exception e) {
            Log.DefaultLogWriteLineError("处理消息时发生异常", e);
        }
    }

    /**
     * 判断字符串是否为JSON格式
     */
    private boolean isJson(String str) {
        try {
            JSONObject.fromObject(str);
            return true;
        } catch (Exception ex) {
            return false;
        }
    }
}
